<template>
  <div>
    <UploadExcel :on-success="onSuccess" />
  </div>
</template>

<script>
import { batchImportEmployees } from '@/api/employees'
export default {
  methods: {
    async onSuccess({ results }) {
      const dictionary = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const data = results.map(item => {
        return this.translateToEn(item, dictionary)
      })
      try {
        if (this.$route.query === 'type=employees') {
          await batchImportEmployees(data)
          this.$message.success('导入成功!')
          setTimeout(() => {
            this.$router.back()
          }, 500)
        } else {
          this.$message.error('未知的导入类型')
        }
      } catch (error) {
        console.dir(error)
      }
    },
    translateToEn(employee, dictionary) {
      const newItem = {}
      for (const key in employee) {
        const newKey = dictionary[key]
        let value = employee[key]
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          // 变成Date对象才能入库
          value = new Date(this.formatDate(value, '/'))
        }
        newItem[newKey] = value
        // newItem[dictionary[key]] = item[key]
      }
      return newItem
    },
    // 处理导入excel后时间格式
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
